package com.yue92.datalife.common;

import com.google.common.hash.Hashing;
import org.springframework.util.StringUtils;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Random;

public class CommonUtil {

    public static String encode(String password) {
        return Hashing.sha256().hashString(password, StandardCharsets.UTF_8).toString();
    }

    public static String generateToken() {
        Random random = new Random();

        return encode(String.valueOf(System.currentTimeMillis()) + random.nextInt());
    }

    public static int getDayIndex(DayOfWeek dayOfWeek) {
        int origin = dayOfWeek.getValue();

        return origin == 7 ? 0 : origin;
    }

    public static LocalDate getLocalDate(@Nullable String recordDate, @Nullable Integer offset, ChronoUnit chronoUnit) {
        LocalDate date;
        if (StringUtils.isEmpty(recordDate)) {
            date = LocalDate.now();
        } else {
            date = LocalDate.parse(recordDate);
        }

        if (offset != null) {
            date = date.plus(offset, chronoUnit);
        }

        return date;
    }
}
